# -*- coding: utf-8 -*-
"""
@Version : 
@Author  : ChenMZ
@Time    : 2025/09/23
@File    : CPULoadPercentageMonitorView.py
@Desc    : 
@Modify  : 
"""
import time

import pyqtgraph
from PyQt5 import QtGui
from typing import Optional
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QWidget, QGridLayout
from ui.DevMonitorUI.CpuMonitor.CpuLoadPercentageMonitorUI import Ui_Form
from model.CpuViewModel.DynamicModel import CpuPercentageGraphViewModel
from tool.signal_bus import CpuMonitorSignalBus


class CpuLoadPercentageView(QWidget, Ui_Form):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # self.plot_widget = QWidget()  # 实例化一个widget部件作为K线图部件
        self.plot_layout = QGridLayout()  # 实例化一个网格布局层
        self.plot_plt = pyqtgraph.PlotWidget()  # 实例化一个绘图部件
        self.paint_thread: GraphPaint = GraphPaint(CpuPercentageGraphViewModel(), self.plot_plt)

        self.initialization()

    def initialization(self):
        # self.plot_widget.setLayout(self.plot_layout)  # 设置线图部件的布局层
        self.plot_plt.setYRange(max=100, min=0)
        self.plot_plt.setBackground("white")
        self.plot_plt.showGrid(x=True, y=True)  # 显示图形网格
        self.plot_layout.addWidget(self.plot_plt)  # 添加绘图部件到线图部件的网格布局层
        # 将上述部件添加到布局层中
        # self.CardWidget.addWidget(self.plot_widget, 1, 0, 3, 3)
        self.CardWidget.setLayout(self.plot_layout)
        self.BodyLabel.setText("%利用率")
        self.BodyLabel_2.setText("时间")

    def register_signal(self):
        pass

    def showEvent(self, a0: Optional[QtGui.QShowEvent]) -> None:
        print("Show CpuLoadPercentageView")
        CpuMonitorSignalBus.signal_dynamic_cap.emit(True)
        if not self.paint_thread.is_act:
            self.paint_thread.start()
        else:
            if not self.paint_thread.is_running:
                self.paint_thread.thread_resume()

    def closeEvent(self, a0: Optional[QtGui.QCloseEvent]) -> None:
        self.paint_thread.thread_end()


class GraphPaint(QThread):
    def __init__(self, model: CpuPercentageGraphViewModel, plt: pyqtgraph.PlotWidget):
        super().__init__()
        self._model = model
        self._plt = plt
        self._activ, self._work = False, False

    @property
    def is_running(self):
        return self._work

    @property
    def is_act(self):
        return self._activ

    def thread_pause(self):
        self._work = False

    def thread_resume(self):
        self._work = True

    def thread_end(self):
        self._work = False
        self._activ = False

    def run(self) -> None:
        self._activ = True
        self._work = True
        canvas = self._plt.plot()
        while self._activ:
            if not self._work:
                time.sleep(.1)
                continue
            canvas.setData(x=self._model.time_list, y=self._model.data, pen="g")
            time.sleep(.5)

